<template>
  <div class="home-goods">
    <GoodsSource/>
    <el-pagination
      @current-change="handlePageChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      background
      layout="prev, pager, next"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useGoodsStore } from '../stores/goods.js';
import GoodsSource from '../components/GoodsSource.vue';

const goodsStore = useGoodsStore();
const goods = ref(goodsStore.goods);
const total = ref(goodsStore.total);
const pageSize = ref(goodsStore.pageSize);
const currentPage = ref(goodsStore.current);
const searchValue = ref(goodsStore.searchValue);

const params = {
  pageNum: currentPage.value,
  pageSize: pageSize.value,
  content: searchValue.value,
};

// 初始化数据
goodsStore.fetchGoods(params);

const handlePageChange = async (val) => {
  currentPage.value = val;
  params.pageNum = val; // 更新分页参数
  await goodsStore.fetchGoods(params);
};

// 监测数据变化并更新相应值
watch(() => goodsStore.goods, (newGoods) => {
  goods.value = newGoods;
});

watch(() => goodsStore.total, (newTotal) => {
  total.value = newTotal;
});

watch(() => goodsStore.pageSize, (newPageSize) => {
  pageSize.value = newPageSize;
});

watch(() => goodsStore.current, (newCurrent) => {
  currentPage.value = newCurrent;
});
</script>

<style lang="less" scoped>
.home-goods {
  width: 1300px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}
</style>
